import json
import time

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from courses.models import Course
from superuser.models import SuperUser
from majing import models, ser


# Create your views here.


class AddCart(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        """
        添加购物车
        """
        # 获取参数
        user = request.user.id
        course_id = request.data.get('course_id')
        if not course_id:
            return Response({"msg": "课程ID不能为空", "code": 400})
        info = Course.objects.filter(id=course_id, is_del=False, status=1).first()
        if not info:
            return Response({"msg": "course_id 无效", "code": 400})
        conn = get_redis_connection('cart')
        cart_key = 'majing:cart:cart_list:' + str(user)
        course_key = 'course:' + str(course_id)
        if conn.hexists(cart_key, course_key):
            return Response({"msg": "已经购买过该商品", "code": 400})
        course_info = {
            'course_id': course_id,
            'course_name': info.name,
            'course_img': str(info.course_img),
            'price': float(info.price),
            'selected': True,
            "add_time": int(time.time()),
            "validity": '永久有效期',
        }
        # 将拼接好的数据添加到redis中
        conn.hset(cart_key, course_key, json.dumps(course_info))
        return Response({"msg": "添加成功", "code": 200, })


class CartList(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        获取购物车列表
        """
        # 1.获取用户信息
        user = request.user
        # 2.判断用户是否有效
        # if not user.is_authenticated:
        #     return Response({"message": "用户未登录", "code": 400})
        # 3.获取购物车key
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        # 4.获取购物车数据
        conn = get_redis_connection('cart')
        cart_info = conn.hgetall(cart_key)
        # 5.判断购物车是的为空
        if not cart_info:
            return Response({"msg": "购物车为空", "code": 400})
        # 处理cart_info的数据 转换为[{},{}]
        # 如果设置了有效期 就是返回有效期  没有设置 [{"expire_time":0,"expire_text":"永久有效","price":原价}]
        cart_list = []
        for course_id, course_info in cart_info.items():
            course_info = json.loads(course_info.decode('utf-8'))
            # 根据课程id拿到有效期列表 如果当前课程没有设置 自己拼接上一个返回一个永久有效
            expire = models.CourseExplain.objects.filter(course_id=course_info['course_id'])
            if expire:
                expire_data = ser.CartSerializer(expire, many=True)
                course_info['expire'] = expire_data.data
            else:
                course_info['expire'] = [{'expire_time': 0, 'expire_text': '永久有效', 'price': course_info['price']}]
            cart_list.append(course_info)
        # 对cartlist进行排序 按照add_time
        cart_list = sorted(cart_list, key=lambda x: x['add_time'], reverse=True)
        return Response({"msg": "获取成功", "code": 200, "data": cart_list})


class CartUpdate(APIView):
    def put(self, request):
        """
        修改购物车
        """
        user = request.user
        course_id = request.data.get('course')
        if not course_id:
            return Response({"msg": "课程ID不能为空", "code": 400})
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        course_key = 'course:' + str(course_id)
        conn = get_redis_connection('cart')
        if not conn.hexists(cart_key, course_key):
            return Response({"msg": "购物车中没有此课程", "code": 400})
        course_info = conn.hget(cart_key, course_key)
        course = json.loads(course_info.decode('utf-8'))
        course['selected'] = not course['selected']
        conn.hset(cart_key, course_key, json.dumps(course))
        return Response({"msg": "修改成功", "code": 200})


class CartDelete(APIView):
    def post(self, request):
        user = request.user
        course_id = request.data.get("course_ids")
        if not course_id:
            return Response({"msg": "传递课程参数", "code": 400})
        # 从购物车中取出这个课程
        cart_key = "majing:cart:cart_list:" + str(user.id)
        course_key = "course:" + str(course_id)
        # 判断这个课程是否在购物车中
        conn = get_redis_connection("cart")
        if not conn.hexists(cart_key, course_key):
            return Response({"msg": "课程不存在", "code": 400})
        # 存在删除这个课程
        try:
            conn.hdel(cart_key, course_key)  # 删除dakey中的xiaokey
            return Response({"msg": "删除成功", "code": 200})
        except:
            return Response("删除失败")


# 全选 不选
class CartSelectAll(APIView):
    def put(self, request):
        """
        全选
        """
        user = request.user
        flag = request.data.get('flag', False)
        # 获取参数 根据当前用户 拿到所有的课程列表 遍历课程列表将状态改为前端传递的 然后塞回去
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        conn = get_redis_connection('cart')
        cart_info = conn.hgetall(cart_key)
        if not cart_info:
            return Response({"msg": "购物车为空", "code": 400})
        cart_list = []
        for course_id, course_info in cart_info.items():
            course_info = course_info.decode('utf-8')
            cart_list.append(json.loads(course_info))
        try:
            for course in cart_list:
                course['selected'] = flag
                course_key = "course:" + str(course['course_id'])
                conn.hset(cart_key, course_key, json.dumps(course))
            return Response({"msg": "修改成功", "code": 200})
        except:
            return Response({"msg": "修改失败", "code": 400})


class OppositeCart(APIView):
    permission_classes = [IsAuthenticated]

    def put(self, request):
        """
        反选
        """
        # 1.获取用户 {user: 1}
        user = request.data.get('user')
        # 2.验证用户有效性
        info = SuperUser.objects.filter(id=user).first()
        if not info:
            return Response({"msg": "用户不存在", "code": 400})
        # 3.获取购物车列表
        cart_key = 'majing:cart:cart_list:' + str(user)
        conn = get_redis_connection('cart')
        cart_info = conn.hgetall(cart_key)
        # 4.判断购物车是否为空
        if not cart_info:
            return Response({"msg": "购物车为空", "code": 400})
        # 5.遍历字典信息 将状态改为反选
        try:
            for course_id, course_info in cart_info.items():
                course_info = json.loads(course_info.decode('utf-8'))
                # 取反
                course_info['selected'] = not course_info['selected']
                # 6.将修改回答数据重新添加到redis中
                course_key = "course:" + str(course_info['course_id'])
                conn.hset(cart_key, course_key, json.dumps(course_info))
            # 7.返回结果
            return Response({"msg": "修改成功", "code": 200})
        except:
            return Response({"msg": "修改失败", "code": 400})


class CartMany(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        """
        批量删除购物车
        """
        user = request.user
        ids = request.data.get('ids')
        if not ids:
            return Response({"msg": "请选择要删除的课程", "code": 400})
        # 1.获取到当前用户的课程信息
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        conn = get_redis_connection('cart')
        cart_info = conn.hgetall(cart_key)
        # 2.遍历字典 如果选中 删除课程 思路一 user
        # try:
        #     for course_id, course_info in cart_info.items():
        #         course_info = course_info.decode('utf-8')
        #         if course_info['selected']:
        #             course_key = "course:" + str(course_id)
        #             conn.hdel(cart_key, course_key)
        # 2.遍历ids 判断ids中是否在字典中 如果在删除 思路二 ids = [1,2,3]
        try:
            for course_id in list(ids):
                course_key = "course:" + str(course_id)
                conn.hdel(cart_key, course_key)
            return Response({"msg": "删除成功", "code": 200})
        except:
            return Response({"msg": "删除失败", "code": 400})


class UpdateExpire(APIView):
    def put(self, request):
        """
        修改购物车有效期
        """
        user = request.user
        course_id = request.data.get('course')
        expire = request.data.get('expire')
        expireprice = request.data.get('expireprice')
        if not course_id:
            return Response({"msg": "请选择要修改的课程", "code": 400})
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        course_key = "course:" + str(course_id)
        conn = get_redis_connection('cart')
        if not conn.hexists(cart_key, course_key):
            return Response({"msg": "课程不存在", "code": 400})
        course_info = conn.hget(cart_key, course_key)
        course = json.loads(course_info.decode('utf-8'))
        course['validity'] = expire
        course['price'] = expireprice
        conn.hset(cart_key, course_key, json.dumps(course))
        return Response({"msg": "修改成功", "code": 200})